package net.buffer;

import net.buffer.BufferManager;
import net.buffer.SByteBuffer;

import java.util.function.Consumer;

//pack len use 1 byte
public class SBytePack {

    private SByteBuffer _buffer;
    private BufferManager _bufferManager;

    public SBytePack(BufferManager bufferManager) {
        _bufferManager = bufferManager;
    }

    public void unpack(SByteBuffer readBuffer, Consumer<SByteBuffer> handle) {
        while (readBuffer.readRemaining() > 0) {
            if (_buffer == null) {
                _buffer = _bufferManager.apply(readBuffer.read());
            }
            SByteBuffer.fill(readBuffer, _buffer);
            if (_buffer.writeRemaining() == 0) {
                handle.accept(_buffer);
                _buffer = null;
            }
        }
    }

    public SByteBuffer pack(SByteBuffer buffer) {
        int size = buffer.readRemaining();
        SByteBuffer nBuffer = _bufferManager.apply(size + 1);
        nBuffer.write((byte) size);
        SByteBuffer.fill(buffer, nBuffer);
        return nBuffer;
    }

    public void dispose() {
        if (_buffer != null)
            _buffer.clear();
        _bufferManager = null;
    }
}
